/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.service;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.MyCrudService;
import com.thinkgem.jeesite.modules.offline.dao.TbOfflinePayDao;
import com.thinkgem.jeesite.modules.offline.entity.TbOfflinePay;
import com.thinkgem.jeesite.modules.product.entity.attribute.TbProductAttribute;
import com.thinkgem.jeesite.modules.sys.dao.*;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 库存管理Service
 *
 * @author huoyan403
 * @version 2016-11-09
 */
@Service
//@Transactional(readOnly = true)
public class TbShopProductService extends MyCrudService<TbShopProductDao, TbShopProduct> {
    @Autowired
    private TbShopProductDao tbShopProductDao;
    @Autowired
    private TbProductMapper tbProductMapper;
    @Autowired
    private TbAgentProductDao tbAgentProductDao;
    @Autowired
    private TbOrderProductMapper tbOrderProductMapper;
    @Autowired
    private TbShopMapper tbShopMapper;
    @Autowired
    private TbMpWalletStreamMapper tbMpWalletStreamapper;
    @Autowired
    private UserTenementInfoDao userTenementInfoDao;
    @Autowired
    private TbOfflinePayDao tbOfflinePayDao;
    @Autowired
    private UserDao userDao;


    public TbShopProduct get(String id) {
        return super.get(id);
    }

    public List<TbShopProduct> findList(TbShopProduct tbShopProduct) {
        return super.findList(tbShopProduct);
    }

    public Page<TbShopProduct> findPage(Page<TbShopProduct> page, TbShopProduct tbShopProduct) {
        tbShopProduct.setPage(page);
        Page<TbShopProduct> proPage = super.findPage(page, tbShopProduct);
        List list = proPage.getList();
        for (int i = 0; i < list.size(); i++) {
            TbShopProduct t = (TbShopProduct) list.get(i);
            //根据商品id得到集合信息
            List<TbProductAttribute> attrList = tbAgentProductDao.queryProductAttributeList(t.getProductId() + "");
            t.setProductAttr(attrList);
        }
        return proPage;
    }

    @Transactional(readOnly = false)
    public void save(TbShopProduct tbShopProduct) {
        super.save(tbShopProduct);
    }

    @Transactional(readOnly = false)
    public void update(TbShopProduct tbShopProduct) {
        try {
/*
            if("on".equals(tbShopProduct.getGender())){
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				tbShopProduct.setGender("1");
				tbShopProduct.setReserveEndTime(sdf.parse(tbShopProduct.getReserveEndTime02()));
				tbShopProduct.setReserveStartTime(sdf.parse(tbShopProduct.getReserveStartTime02()));
			}else{
				tbShopProduct.setGender("0");
				tbShopProduct.setReserveEndTime(DateTimeUtils.getDateYYYY_MM_DD_HH_MM_SS(tbShopProduct.getReserveEndTime01()));
				tbShopProduct.setReserveStartTime(DateTimeUtils.getDateYYYY_MM_DD_HH_MM_SS(tbShopProduct.getReserveStartTime01()));
			}*/
            super.update(tbShopProduct);
        } catch (Exception e) {

        }
    }

    @Transactional(readOnly = false)
    public void delete(TbShopProduct tbShopProduct) {
        super.delete(tbShopProduct);
    }

    @Transactional(readOnly = false)
    public void updateStatus(TbShopProduct tbShopProduct) {
        tbShopProductDao.updateStatus(tbShopProduct);
    }

    public TbShopProduct selectProByProId(Integer productId, String attr) {
        TbShop shop = new TbShop();
        shop.setUid(UserUtils.getUser().getId());
        TbShop tbShop = tbShopMapper.selectByUid(shop);
        TbShopProduct tbShopProduct = new TbShopProduct();
        tbShopProduct.setShopId(tbShop.getId());
        tbShopProduct.setProductId(productId);
        tbShopProduct.setAttr(attr);
        return tbShopProductDao.selectProByProId(tbShopProduct);
    }

    @Transactional(readOnly = false)
    public void insertProWithAgentPro(String productId) {
        TbProduct tbPro = tbProductMapper.selectByProId(Integer.valueOf(productId));
        TbShop tbShop = new TbShop();
        tbShop.setUid(UserUtils.getUser().getId());
        TbShop shop = tbShopMapper.selectByUid(tbShop);
        TbShopProduct tbShopProduct = new TbShopProduct();
        tbShopProduct.setGender(tbPro.getGender());
        tbShopProduct.setReserveFlag(new Byte("1"));
        tbShopProduct.setGender(tbPro.getGender());
        tbShopProduct.setShopId(shop.getId());
        tbShopProduct.setReserveStartTime(tbPro.getReserveStartTime());
        tbShopProduct.setReserveEndTime(tbPro.getReserveEndTime());
        tbShopProduct.setProductId(tbPro.getId());
        tbShopProduct.setPrice(tbPro.getWholesalePrice());
        tbShopProduct.setIsUseMqWallet(tbPro.getIsUseMqWallet());
        tbShopProduct.setCreateTime(new Date());
        tbShopProduct.setUpdateTime(new Date());
        tbShopProduct.setAttr(tbPro.getProductDesc());
        tbShopProduct.setColor(tbPro.getProductDesc());
        tbShopProduct.setStatus(0);
        tbShopProduct.setIsDelete(new Byte("0"));
        tbShopProduct.setProductAttr(tbPro.getProductAttr());
        tbShopProduct.setProductSize(tbPro.getSize());
        tbShopProductDao.insertPro(tbShopProduct);
    }

    @Transactional(readOnly = false)
    public void inserMpWallet(TbUser tbUser) {
        //麻雀钱包充值
        tbShopProductDao.insetMpWallet(tbUser);
        //麻雀钱包流水
        TbMpWalletStream tbMpWalletStream = new TbMpWalletStream();
        tbMpWalletStream.setUid(tbUser.getUid() + "");
        tbMpWalletStream.setChangeMoney(tbUser.getMqtotalMoney());
        tbMpWalletStream.setPayType("4");//现金
        tbMpWalletStream.setType("0");//收入
        tbMpWalletStream.setCategory("11");//麻雀钱包线下充值
        tbMpWalletStream.setIsDelete(new Byte("0"));
        Date date = new Date();
        tbMpWalletStream.setCreateTime(date);
        tbMpWalletStream.setUpdateTime(date);
        tbMpWalletStreamapper.insert(tbMpWalletStream);

    }

    @Transactional(readOnly = false)
    public void inserTenemetWallet(TbUser tbUser) {
        //物业钱包充值
        tbShopProductDao.insetTenementWallet(tbUser);
        //物业钱包流水
        TbTenementWalletStream tbTenementWalletStream = new TbTenementWalletStream();
        tbTenementWalletStream.setUid(tbUser.getUid());
        tbTenementWalletStream.setType("0");
        tbTenementWalletStream.setCategory("13");//物业钱包线下充值
        tbTenementWalletStream.setChangeMoney(tbUser.getMqtotalMoney());
        Date date = new Date();
        tbTenementWalletStream.setIsDelete(new Byte("0"));
        tbTenementWalletStream.setCreateTime(date);
        tbTenementWalletStream.setUpdateTime(date);
        tbTenementWalletStream.setPayType("4");//现金充值
        tbShopProductDao.inserTenementStream(tbTenementWalletStream);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getProductByBarcode(String num, String userId) {
        User user = this.userDao.queryUser(userId);
        if (!StringUtils.isEmpty(user.getShopId())){
            userId = user.getShopId();
        }
        return tbShopProductDao.selectProductByBarcodeAndUserId(num, userId);
    }

    @Transactional(readOnly = true)
    public TbUser getTbUserByPhone(String phone) {
        TbUser tbUser = tbShopProductDao.getTbUserByPhone(phone);
        if (null == tbUser.getAddress() || "".equals(tbUser.getAddress())) {
            tbUser.setAddress("无");
        }
        return tbUser;
    }

    @Transactional(readOnly = false)
    public Map<String, Object> updateProductStoreCount(JSONObject json, String userId, Integer payId, String payName, String sumMoney, String paySum, String mobile, String code) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Map<String, Object> sqlMap = new HashMap<String, Object>();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        StringBuffer alerMessage = new StringBuffer();
        Iterator<String> msgIterator = json.keys();
        boolean isInsertOrder = false;
        Integer orderId = 0;
        Date now = new Date();
        if (!StringUtils.isEmpty(UserUtils.getUser().getShopId())){
            userId = UserUtils.getUser().getShopId();
        }
        while (msgIterator.hasNext()) {
            String key = msgIterator.next();
            JSONObject obj = (JSONObject) json.get(key);

            Iterator<String> msgIteratorColor = obj.keys();
            while (msgIteratorColor.hasNext()) {
                String keyColor = msgIteratorColor.next();
                Map<String, Object> map = tbShopProductDao.selectProductByBarcodeAndColorAndUserId(key, keyColor, userId);
                if (!isInsertOrder) {
                    //商品订单
                    TbOfflineShoppingOrderLog log = new TbOfflineShoppingOrderLog();
                    log.setShopId((Integer) map.get("shopId"));
                    log.setUserId(userId);
                    log.setOrderNum(format.format(now));
                    log.setOrderSum(new BigDecimal(sumMoney));
                    log.setPayMoney(new BigDecimal(paySum));
                    if (payId == 3) {
                        log.setGiveMoney(new BigDecimal(paySum).subtract(new BigDecimal(sumMoney)));
                    } else {
                        log.setGiveMoney(new BigDecimal(sumMoney));
                    }
                    log.setCreateTime(now);
                    log.setPayType(payId);
                    log.setPayName(payName);
                    tbShopProductDao.insertShoppinOrderLog(log);
                    orderId = log.getId();
                    resultMap.put("orderId", orderId);
                    isInsertOrder = true;
                    subWyWallet(userId, payId, log.getGiveMoney(), mobile, code);
                }
                //商品订单详情
                TbOfflineShoppingOrderInfo info = new TbOfflineShoppingOrderInfo();
                info.setOrderId(orderId);
                info.setProductTitle((String) map.get("title"));
                info.setProductNum(Integer.parseInt(String.valueOf(obj.get(keyColor))));
                info.setProductColor((String) map.get("color"));
                info.setProductPrice((BigDecimal) map.get("price"));
                info.setProductSum(((BigDecimal) map.get("price")).multiply(new BigDecimal(Integer.parseInt(String.valueOf(obj.get(keyColor))))));
                tbShopProductDao.insertShoppinOrderInfo(info);
                Integer id = Integer.parseInt(String.valueOf((Long) map.get("id")));
                sqlMap.put("id", id);
                if ((Integer) map.get("isMainTainStoreNum") == 1 && map.get("alertStoreNum") != null) {
                    Integer newStoreNum = (Integer) map.get("storeNum") - Integer.parseInt(String.valueOf(obj.get(keyColor)));
                    sqlMap.put("storeNum", newStoreNum);
                    if (newStoreNum < (Integer) map.get("alertStoreNum")) {
                        TbMsgNotify msg = new TbMsgNotify();
                        msg.setTitle("门店线下商品库存预警");
                        msg.setContent(map.get("title") + "/" + map.get("color") + "的数量低于预警，请及时补充");
                        msg.setStatus("0");
                        msg.setUid(userId);
                        msg.setCreateTime(now);
                        msg.setUpdateTime(now);
                        tbShopProductDao.insertMsgNotify(msg);
                        alerMessage.append("," + map.get("title") + "/" + map.get("color"));
                    }
                } else {
                    sqlMap.put("storeNum", (Integer) map.get("storeNum"));
                }
            }


            sqlMap.put("updateTime", now);
            tbShopProductDao.updateShopProduct(sqlMap);
        }
        if (alerMessage.length() != 0) {
            alerMessage.append("的数量低于预警，请及时补充");
        }
        resultMap.put("message", alerMessage.toString());
        return resultMap;
    }

    private void subWyWallet(String userId, Integer payId, BigDecimal giveMoney, String mobile, String code) {
        if (payId != 4 && payId != 5) {
            return;
        }


        TbOfflinePay query = new TbOfflinePay();
        query.setCode(mobile + code);
        query.setStatus("0");

        List<TbOfflinePay> tbOfflinePay = this.tbOfflinePayDao.findList(query);
        if (tbOfflinePay == null || tbOfflinePay.size() == 0) {
            throw new RuntimeException("非法结算数据！");
        }

        TbOfflinePay offlinePay = tbOfflinePay.get(0);

        if (!offlinePay.getStatus().equals("0")){
            throw new RuntimeException("支付码无效！");
        }

        if (new BigDecimal(offlinePay.getAmount()).compareTo(giveMoney) != 0 ){
            throw new RuntimeException("结算金额不一致！");
        }




        TbUser tbuser = this.getTbUserByPhone(mobile);


        if (payId.intValue() == 4) {//物业钱包


            tbuser.setMqtotalMoney(BigDecimal.ZERO.subtract(giveMoney));
            int result  = this.tbShopProductDao.insetTenementWallet(tbuser);
            if(result == 0){
                throw new RuntimeException("物业钱包金额不足！");

            }
            TbTenementWalletStream tbTenementWalletStream = new TbTenementWalletStream();
            tbTenementWalletStream.setUid(tbuser.getUid());
            tbTenementWalletStream.setType("0");
            tbTenementWalletStream.setCategory("4");
            tbTenementWalletStream.setChangeMoney(giveMoney);
            Date date = new Date();
            tbTenementWalletStream.setIsDelete(new Byte("0"));
            tbTenementWalletStream.setCreateTime(date);
            tbTenementWalletStream.setUpdateTime(date);
            tbTenementWalletStream.setPayType("1");
            tbShopProductDao.inserTenementStream(tbTenementWalletStream);

            //给当前登录用户相关门店增加物业钱包金额
            TbMpWalletStream tbMpWalletStream = new TbMpWalletStream();
            User user = UserUtils.getUser();
            if (StringUtils.isEmpty(user.getShopId())) {//店铺老板
                tbMpWalletStream.setUid(user.getId());
                this.tbShopProductDao.updateMpWallet(user.getId(), giveMoney.multiply(new BigDecimal("0.6")));
            } else {//收银员
                tbMpWalletStream.setUid(user.getShopId());
                this.tbShopProductDao.updateMpWallet(user.getShopId(), giveMoney.multiply(new BigDecimal("0.6")));
            }

            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setPayType("0");
            tbMpWalletStream.setType("0");
            tbMpWalletStream.setCategory("4");
            tbMpWalletStream.setChangeMoney(giveMoney.multiply(new BigDecimal("0.6")));

            tbMpWalletStream.setIsDelete(Byte.valueOf("0"));
            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setUpdateTime(new Date());
            this.tbMpWalletStreamapper.insertSelective(tbMpWalletStream);
        } else if (payId.intValue() == 5) {
            //扣除该用户物业钱包金额。
            if (tbuser.getMqtotalMoney().compareTo(giveMoney) == -1){
                throw new RuntimeException("麻雀钱包金额不足！");
            }

            this.tbShopProductDao.updateMpWallet(tbuser.getUid().toString(), BigDecimal.ZERO.subtract(giveMoney));
            TbMpWalletStream tbMpWalletStream = new TbMpWalletStream();
            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setPayType("1");
            tbMpWalletStream.setType("0");
            tbMpWalletStream.setCategory("4");
            tbMpWalletStream.setChangeMoney(giveMoney);
            tbMpWalletStream.setUid(tbuser.getId());
            tbMpWalletStream.setIsDelete(Byte.valueOf("0"));
            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setUpdateTime(new Date());
            this.tbMpWalletStreamapper.insertSelective(tbMpWalletStream);

            tbMpWalletStream = new TbMpWalletStream();
            User user = UserUtils.getUser();
            if (StringUtils.isEmpty(user.getShopId())) {//店铺老板
                tbMpWalletStream.setUid(user.getId());
                this.tbShopProductDao.updateMpWallet(user.getId(), giveMoney);
            } else {//收银员
                tbMpWalletStream.setUid(user.getShopId());
                this.tbShopProductDao.updateMpWallet(user.getShopId(), giveMoney);
            }
            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setPayType("0");
            tbMpWalletStream.setType("0");
            tbMpWalletStream.setCategory("4");
            tbMpWalletStream.setChangeMoney(giveMoney);
            tbMpWalletStream.setUid(user.getId());
            tbMpWalletStream.setIsDelete(Byte.valueOf("0"));
            tbMpWalletStream.setCreateTime(new Date());
            tbMpWalletStream.setUpdateTime(new Date());
            this.tbMpWalletStreamapper.insertSelective(tbMpWalletStream);
        }

        offlinePay.setStatus("1");
        this.tbOfflinePayDao.update(offlinePay);
    }


    public List<TbShopProduct> findAllProByShopId(String shopId) {
        return tbShopProductDao.findAllProByShopId(shopId);
    }

    public Page<ReverseProduct> selectReverseProductList(Page<ReverseProduct> reverseProductPage, ReverseProduct reverseProduct) {

        reverseProduct.setPage(reverseProductPage);
        List<ReverseProduct> reverseProductList = tbShopProductDao.selectReverseProductList(reverseProduct);
        reverseProductPage.setList(reverseProductList);
        return reverseProductPage;
    }

    public Page<TbShopProduct> exportProduct(Page<TbShopProduct> page, TbShopProduct tbShopProduct) {
        Page<TbShopProduct> proPage = super.findPage(page, tbShopProduct);
        for (int i = 0; i < proPage.getList().size(); i++) {
            TbShopProduct tt = proPage.getList().get(i);
            if (tt.getReflage().equals("4")) {
                tt.setReflage("便利生活");
            }
            if (tt.getReflage().equals("3")) {
                tt.setReflage("生活预定");
            }
            if (tt.getIsUseMqWallet() == 0) {//0否1是
                tt.setIsWyMallet("否");
            }
            if (tt.getIsUseMqWallet() == 1) {//0否1是
                tt.setIsWyMallet("是");
            }
        }
        return proPage;
    }

    @Transactional(readOnly = false)
    public int deleteProWithAgentPro(TbShopProduct tbShopProduct) {
        int count = tbShopProductDao.delete(tbShopProduct);
        if (count > 0) {
            return count;
        }
        return 0;
    }
    @Transactional(readOnly = false)
    public int updateProductPriceById(Integer id,String price) {
        int count = tbShopProductDao.updateProductPriceById(id,price);
        if(count>0){
            return count;
        }
        return 0;
    }
}